from django.shortcuts import render
import json
from pathlib import Path
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from resumeopt_sys.models import History
from account_sys.models import User
from enterprise_sys.models import *
from utils.response_utils import build_response
from utils.session_utils import has_login, get_login_user
from openai import OpenAI
# Create your views here.

client = OpenAI(
    api_key = "sk-wFdoL3MNvYcoZdKWDLbMUHu4bPvL3UsrW4C9lrZ46pdfgxA8",
    base_url = "https://api.moonshot.cn/v1",
)
@csrf_exempt
@api_view(['POST'])
def optimize_resume(request):
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')

    user = get_login_user(request)
    file = request.FILES.get('file')

    if not file:
        return build_response(errno=4001, msg='未提供文件')

    # 保存文件到临时目录
    file_name = default_storage.save(file.name, ContentFile(file.read()))
    file_path = default_storage.path(file_name)

    # try:
    # 使用 Moonshot API 提取文件内容
    file_object = client.files.create(file=Path(file_path), purpose="file-extract")
    file_content = client.files.content(file_id=file_object.id).text

    # 使用 Moonshot API 优化简历内容
    messages = [
        {
            "role": "system",
            "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。",
        },
        {
            "role": "system",
            "content": file_content,
        },
        {"role": "user", "content": "请优化此简历内容"},
    ]

    completion = client.chat.completions.create(
        model="moonshot-v1-32k",
        messages=messages,
        temperature=0.3,
    )

    optimized_content = completion.choices[0].message.content

    # 删除临时文件
    default_storage.delete(file_name)

    # 保存优化内容到历史记录
    History.objects.create(user=user, content=optimized_content)

    return build_response(other_info={'optimized_content': optimized_content}, msg='简历优化成功')

@csrf_exempt
@api_view(['GET'])
def get_history(request):
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')

    user = get_login_user(request)
    history_records = History.objects.filter(user=user).order_by('-created_at')

    history_list = [record.parse_dict() for record in history_records]
    return build_response(other_info={'history': history_list}, msg='获取历史记录成功')